# API Docs: https://reqable.com/docs/capture/addons

from reqable import *
import mysql.connector
import json
import requests
import base64

def onRequest(context, request):
  # Print url to console
  print('request url     : ' + context.url)
  print('request.headers : ' + request.headers)
  # tempJson = request.headers.toJson()
  # log_json_array = request.headers.toJson()
  
  # print('log_json_array：'+ log_json_array['authorization'])
  if request.headers['authorization'] is not None:
    print(request.headers['authorization'])
    
    if request.headers['authorization'] is not None:
      json_data = {
          'refresh': request.headers['authorization'].replace("Bearer ",""),
      }
      
      global_headers = {
        'Host': 'gateway.blum.codes',
        'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99", "Microsoft Edge WebView2";v="124"',
        'accept': 'application/json, text/plain, */*',
        'content-type': 'application/json',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
        'sec-ch-ua-platform': '"Windows"',
        'origin': 'https://telegram.blum.codes',
        'sec-fetch-site': 'same-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'priority': 'u=1, i',
      }
      print("刷新111")
      response = requests.post('https://gateway.blum.codes/v1/auth/refresh', headers=global_headers, json=json_data, verify=False)
      print("刷新结果")
      print(response.content)
      refrest_response_json = json.loads(response.content)

      if "access" in refrest_response_json:
        # 刷新token成功
        access_token = refrest_response_json['access']
        refreshedAccessToken = "Bearer " + refrest_response_json['access']
        
        refresh_token = refrest_response_json['refresh']
        refreshedRefreshToken = "Bearer " + refrest_response_json['refresh']
        
        print("刷新到的 REFRESH TOKEN：", refreshedAccessToken )

        # 解析刚获取到的access token, 用.号进行split
        access_token_splited = access_token.split(".")
        access_token_splited_token_index1 = access_token_splited[1]
        
        # 解析刚获取到的refresh token, 用.号进行split
        refresh_token_splited = refresh_token.split(".")
        refresh_token_splited_token_index1 = refresh_token_splited[1]

        # base64解析 access token
        access_token_splited_token_index1 += "=" * ((4 - len(access_token_splited_token_index1) % 4) % 4)
        access_token_decoded_string = base64.b64decode(access_token_splited_token_index1)
        access_token_decoded_string_utf8 = access_token_decoded_string.decode("utf-8")

        access_token_parsed_token_json = json.loads(access_token_decoded_string_utf8)

        access_token_token_expire_timestamp = access_token_parsed_token_json['exp']
        game_id = access_token_parsed_token_json['sub']
        
        # base64解析 refresh token
        refresh_token_splited_token_index1 += "=" * ((4 - len(refresh_token_splited_token_index1) % 4) % 4)
        refresh_token_decoded_string = base64.b64decode(refresh_token_splited_token_index1)
        refresh_token_decoded_string_utf8 = refresh_token_decoded_string.decode("utf-8")

        refresh_token_parsed_token_json = json.loads(refresh_token_decoded_string_utf8)

        refresh_token_token_expire_timestamp = refresh_token_parsed_token_json['exp']
        
        payload = {
                "game_id":""+game_id,
                "access_token":refreshedAccessToken,
                "access_token_expire":access_token_token_expire_timestamp,
                "refresh_token":refreshedRefreshToken,
                "refresh_token_expire":refresh_token_token_expire_timestamp
        }
        
        headers_a = {
          'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",
          'Accept': "application/json, text/plain, */*",
          'Accept-Encoding': "gzip, deflate, br, zstd",
          'Content-Type': "application/json",
          'sec-ch-ua': "\"Chromium\";v=\"124\", \"Microsoft Edge\";v=\"124\", \"Not-A.Brand\";v=\"99\", \"Microsoft Edge WebView2\";v=\"124\"",
          'sec-ch-ua-mobile': "?0",
          'sec-ch-ua-platform': "\"Windows\"",
          'sec-fetch-site': "same-site",
          'sec-fetch-mode': "cors",
          'sec-fetch-dest': "empty",
          'accept-language': "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
          'priority': "u=1, i"
        }
        
        update_result_response = requests.post('http://43.134.224.49/api/blum/token', headers=headers_a, json=payload, verify=False, timeout=8)
        print(payload)
        print(update_result_response.content)      
        print("写入数据库成功！")
      else:
        print("ppppp")
  return request

def onResponse(context, response):

  return response

